package com.demotest.service.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import gui.ava.html.image.generator.HtmlImageGenerator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

public class ImageUtil {

    private static Configuration cfg;

    static {
        try {
            //初始化FreeMarker配置
            cfg = new Configuration();
            //设置FreeMarker的模版文件位置
            cfg.setDirectoryForTemplateLoading(new File(FileUtil.getResourcePath("") + "ftl"));
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取模板
     * @param templateName 模板名，如test.ftl
     * @return
     */
    public static Template getTemplate(String templateName) {
        Template t = null;
        try {
            t = cfg.getTemplate(templateName);
            t.setEncoding("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * HTML转图片
     * @param outputPath 输出路径
     * @param imageName 图片名称
     * @param data 填充数据
     * @param template html模板
     * @return
     */
    public static String htmlToImage(String outputPath, String imageName, Map<String,String> data, Template template){
        if (template == null){
            throw new RuntimeException("The template is not found ...");
        }

        File file = new File(outputPath);
        if (file.exists()) {
            if (!file.isDirectory()){
                throw new RuntimeException("The parameter 'outputPath' is not a folder ...");
            }
        }else {
            file.mkdirs();
        }

        try {
            String outputFile = outputPath + File.separator + imageName + ".png";
            StringWriter stringWriter = new StringWriter();
            BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
            template.process(data, bufferedWriter);
            bufferedWriter.flush();
            bufferedWriter.close();

            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(stringWriter.toString());
            imageGenerator.saveAsImage(outputFile);
            return outputFile;
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
